package Security;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Encoding {
	
	public static final String md5(String password) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(password.getBytes());
		
		byte byteData[] = md.digest();
		
		StringBuffer hexString = new StringBuffer();
		for (int i = 0 ; i < byteData.length ; i++) {
			String hex = Integer.toHexString(0xff & byteData[i]);
			if(hex.length()==1) hexString.append('0');
			hexString.append(hex);
		}
		
		return hexString.toString();
	}
	
	public static final String hashAndSalt(String password, String salt) {
		try {
			String salted_pw = salt + password;
			MessageDigest md = MessageDigest.getInstance("SHA-256"); // algorithm specification
			md.update(salted_pw.getBytes("UTF-8")); // update for byte representation
			
			byte[] byteData = md.digest();
			
			StringBuffer hexString = new StringBuffer();
			for (int i = 0 ; i < byteData.length ; i++) {
				String hex = Integer.toHexString(0xff & byteData[i]);
				if(hex.length()==1) hexString.append('0');
				hexString.append(hex);
			}
			
			return hexString.toString();
		} 
		catch(NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		catch(UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		return ""; //dummy value so it doesn't complain (hexString local to try statement)
	}

}
